﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Management;

namespace Setup.UC
{
    public partial class Progress : UserControl
    {
        System.Threading.Thread thread = null;
        public Progress()
        {
            InitializeComponent();
            this.ProgressCheck += Progress_ProgressCheck;
            if (Logic.Type == OperationType.Update)
                this.checkBox1.Checked = true;
            this.Disposed += Progress_Disposed;
            checkBox1.Text = "安装完成之后打开";
            //if (Logic.Install != null)
            //    checkBox1.Text = "安装完成之后打开" + Logic.Install.DisplayName;
        }

        void Progress_Disposed(object sender, EventArgs e)
        {
            if (thread != null && thread.ThreadState == System.Threading.ThreadState.Running)
                thread.Abort();
        }

        /// <summary>
        /// 进度
        /// </summary>
        /// <param name="current"></param>
        /// <param name="total"></param>
        /// <param name="tip"></param>
        void Progress_ProgressCheck(Point current, Point total, string tip)
        {
            this.Invoke(new Action(() =>
            {
                if (current.X > current.Y)
                    current.X = current.Y;
                if (total.X > total.Y)
                    total.X = total.Y;
                if (current.X >= current.Y && total.X >= total.Y)
                {
                    this.progressBarCurrent.Maximum = current.Y;
                    this.progressBarCurrent.Value = current.Y;
                    this.progressBarTotal.Maximum = total.Y;
                    this.progressBarTotal.Value = total.Y;
                    this.button3.Enabled = true;
                    label5.Text = "操作完成";
                }
                else
                {
                    this.progressBarCurrent.Maximum = current.Y;
                    this.progressBarCurrent.Value = current.X;
                    this.progressBarTotal.Maximum = total.Y;
                    this.progressBarTotal.Value = total.X;
                    label5.Text = tip;
                }
            }));
        }
        public Form1 MainForm { get; set; }

        private void button3_Click(object sender, EventArgs e)
        {
            if (checkBox1.Visible && checkBox1.Checked)
                if (System.IO.File.Exists(Logic.Install.InstallLocation + Logic.Install.Main))
                {
                    System.Diagnostics.Process proc = new Process();
                    proc.StartInfo.WorkingDirectory = Logic.Install.InstallLocation;
                    proc.StartInfo.FileName = Logic.Install.InstallLocation + Logic.Install.Main;
                    proc.Start();
                }

            Logic.MainForm.Complete();
        }

        private void Progress_Load(object sender, EventArgs e)
        {
            if (Logic.Install != null)
                label1.Text = "正在更新" + Logic.Install.DisplayName;
        }

        public void Exec()
        {
            label5.Text = "正在验证.....";
            if (Logic.Type == OperationType.UnInstall)
                this.checkBox1.Visible = false;
            thread = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
             {
                 //关闭相应的进程
                 ProcessLogic.CloseProcess(Logic.Install.CloseProcesss.ToArray());
                 switch (Logic.Type)
                 {
                     case OperationType.Install:
                         Install();
                         break;
                     case OperationType.Update:
                         InUpdate();
                         break;
                     case OperationType.UnInstall:
                         UnInstall();
                         break;
                 }
             }));
            thread.Start();
        }

        private void Install()
        {
            InstallInfo info = Logic.Install;
            if (!info.InstallLocation.EndsWith("\\") && !info.InstallLocation.EndsWith("/"))
                info.InstallLocation += "\\";
            if (!info.InstallLocation.Contains(info.DisplayName))
                info.InstallLocation += info.DisplayName + "\\";

            if (Directory.Exists(info.InstallLocation))
            {
                FileLogic.AddSecurityControll2DirectoryInfo(info.InstallLocation);
                Directory.Delete(info.InstallLocation, true);
            }

            Directory.CreateDirectory(info.InstallLocation);
            FileLogic.AddSecurityControll2DirectoryInfo(info.InstallLocation);
            int totalIndex = 0;
            if (string.IsNullOrEmpty(info.Main))
                this.checkBox1.Checked = true;
            foreach (var item in info.Files)
            {
                totalIndex++;
                string tip = "加载[" + item.name + "].....";
                progressCheck(new Point(1, 100), new Point(totalIndex, info.Files.Count), tip);
                string fileName = info.InstallLocation + item.name;
                FileLogic.DownloadFile(item.url, fileName, (point) => {
                    progressCheck(point, new Point(totalIndex, info.Files.Count), tip);
                });
            }

            //添加注册表
            RegistryLogic.Install(Logic.Install);

            //保存安装信息
            Logic.Install.Save(info.InstallLocation + "setup.xml");

            //添加防火墙白名单
            if (!string.IsNullOrEmpty(Logic.Install.Main) && System.IO.File.Exists(Logic.Install.InstallLocation + Logic.Install.Main))
                FirewallLogic.FirewallAddRule(Logic.Install.InstallLocation + Logic.Install.Main, true);

            //创建快捷方式
            LinkLogic.SetLinks();
            System.Threading.Thread.Sleep(2000);
        }
        private void InUpdate()
        {
            InstallInfo info = Logic.Install;
            if (string.IsNullOrEmpty(info.Main))
                this.checkBox1.Checked = true;
            if (!Directory.Exists(info.InstallLocation))
                Directory.CreateDirectory(info.InstallLocation);
            FileLogic.AddSecurityControll2DirectoryInfo(info.InstallLocation);

            int totalIndex = 0;
            foreach (var item in info.Files)
            {
                string tip = "正在更新[" + item.name + "].....";
                progressCheck(new Point(1, 100), new Point(totalIndex, info.Files.Count), tip);
                totalIndex++;

                if (FileLogic.Md5Equals(item.md5, info.InstallLocation + item.name))
                {
                    progressCheck(new Point(100, 100), new Point(totalIndex, info.Files.Count), tip);
                    continue;
                }
                progressCheck(new Point(23, 100), new Point(totalIndex, info.Files.Count), tip);
                string fileName = info.InstallLocation + item.name;
                FileLogic.DownloadFile(item.url,fileName,point=> progressCheck(point, new Point(totalIndex, info.Files.Count), tip));
            }

            //创建快捷方式
            LinkLogic.SetLinks();

            //更新注册表
            RegistryLogic.Install(Logic.Install);

            //更新安装信息
            Logic.Install.Save(info.InstallLocation + "setup.xml");
            System.Threading.Thread.Sleep(2000);
        }
        private void UnInstall()
        {
            InstallInfo info = Logic.Install;
            if (Directory.Exists(info.InstallLocation))
            {
                FileLogic.AddSecurityControll2DirectoryInfo(info.InstallLocation);
                //string[] files = Directory.GetFiles(info.InstallLocation);
                progressCheck(new Point(1, 1), new Point(1, 100), "正在卸载...");

                foreach (var item in info.links)
                    if (System.IO.File.Exists(item.destination + ".lnk"))
                        try
                        {
                            System.IO.File.Delete(item.destination + ".lnk");
                        }
                        catch (Exception)
                        {
                        }

                try
                {
                    Directory.Delete(info.InstallLocation, true);
                }
                catch (Exception)
                {
                }
            }
            RegistryLogic.UnInstall(info);
            progressCheck(new Point(1, 1), new Point(1, 1), "卸载完成");
        }




        private Action<Point, Point, string> progressCheck;
        private event Action<Point, Point, string> ProgressCheck
        {
            add
            {
                progressCheck += value;
            }
            remove
            {
                progressCheck -= value;
            }
        }

    }
}
